angular.module('app.services')
    .factory('HttpService', ['$log', '$http', '$q', '$state', 'UserAuth', 'ApiUrl', 'Util',function ($log, $http, $q, $state, UserAuth, ApiUrl, Util) {
        //刷新token
        var refreshToken = function () {
            var apiObj = ApiUrl.refreshToken;
            var options = {
                url: apiObj.url,
                method: apiObj.method,
                headers: {
                    Authorization: 'Bearer ' + UserAuth.getUserAuth().token || ''
                }
            };
            var d = $q.defer();
            $http(options).then(function (response) {
                $log.debug('refresh token success', response);
                UserAuth.saveUserAuth({token: response.data.token});
                d.resolve();
            }, function (response) {
                d.reject();
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
            return d.promise;
        };
        // 访问http
        var apiCall = function (opts, noAuth) {
            var options = opts;
            var noAuth = noAuth;
            return function () {
                var m = $q.defer();
                if (!noAuth) {
                    options.headers = {
                        Authorization: 'Bearer ' + UserAuth.getUserAuth().token || ''
                    }
                }
                $http(options).then(function (response) {
                    $log.debug('send ' + opts.url, response);
                    m.resolve(response.data);
                }, function (response) {
                    $log.debug('request error', response);
                    if (response.status == '401') {
                        if( options.url == ApiUrl.login.url ){
                            m.reject(response);
                            return;
                        }
                        var qRefresh = refreshToken();
                        qRefresh.then(function () {
                            $log.debug('refresh token success', UserAuth.getUserAuth().token);
                            m.reject({refresh: 'ok'});
                        }, function () {
                            $log.debug('refresh token failed');
                            m.reject({refresh: 'error'});
                            $state.go('login');
                        })
                    } else if (response.status == '429') {
                        Util.popup({content: '请求太频繁，请稍后再试'});
                        m.reject(response);
                    } else if (response.status == '422') {
                        for (var key in response.data.errors) {
                            Util.popup({content: response.data.errors[key][0]});
                            m.reject(response);
                            return;
                        }
                    }  if(response.status == '400'){
                        Util.popup({content: response.data.message });
                        m.reject(response);
                        return;
                    }else {
                        m.reject(response);
                    }
                });
                return m.promise;
            }
        };
        return {
            //url call template
            accessAPI: function (apiObj, opt) {
                var d = $q.defer(),
                    url = apiObj.url,
                    method = apiObj.method,
                    opt = opt || {},
                    path = opt.path,
                    msg = opt.body,
                    query = opt.query;
                var tempMsg = {};
                angular.forEach( msg, function(value, key){
                    if( value == 0 ){
                        tempMsg[key] = value;
                    }else if(value){
                        tempMsg[key] = value;
                    }
                });
                if (path) {
                    angular.forEach(path, function (value, key) {
                        url = url.replace(':' + key, value);
                    })
                }
                if (query&&!Util.isEmptyObject(query)) {
                    var i=0;
                    angular.forEach(query, function (value, key) {
                        if(value!==""&&value!==undefined&&value!==null){
                            if(i==0){
                                url+='?'+key+'=' + value ;
                            }else {
                                url+='&'+key+'=' + value ;
                            }
                            i++;
                        }
                    })
                }
                var options = {
                    method: method,
                    url: url,
                    data: tempMsg
                };
                var _apiCall = apiCall(options, opt.noAuth);
                var defer = _apiCall();
                defer.then(function (result) {
                    d.resolve(result);
                }, function (reason) {

                    if (reason.refresh) {
                        if (reason.refresh === 'ok' && !opt.noAuth ) {
                            defer = _apiCall();
                            defer.then(function (result) {
                                $log.debug('call api again success', result);
                                d.resolve(result);
                            }, function (reason) {
                                d.reject(reason);
                                $state.go('login');
                            })
                        } else {
                            d.reject(reason);
                            $state.go('login');
                        }
                    } else {
                        d.reject(reason);
                    }
                })
                return d.promise;
            },


        }
    }]);